#include "power_orb.h"

#include <QLabel>
#include <QLineEdit>
#include <QSpinBox>
#include <QToolButton>
#include <QVBoxLayout>

/**
 * PowerOrbWidget
 */
PowerOrbWidget::PowerOrbWidget( QWidget * parent )
    : QWidget( parent ) {
    orbSpinBox = new QSpinBox{ this };
    orbSpinBox->setSizePolicy( QSizePolicy::Policy::Preferred, QSizePolicy::Policy::Fixed );
    orbSpinBox->setMaximum( 30 );
    orbSpinBox->setPrefix( "Orbs claimed: " );
    orbSpinBox->setSuffix( " / 30" );
    // disable highlighting
    QLineEdit * l = orbSpinBox->findChild<QLineEdit *>();
    l->setReadOnly( true );
    connect( orbSpinBox, QOverload<int>::of( &QSpinBox::valueChanged ), l, &QLineEdit::deselect, Qt::QueuedConnection );
    connect( l, &QLineEdit::cursorPositionChanged, l, [l]() { l->deselect(); }, Qt::QueuedConnection );

    cost = new QWidget{ this };
    QHBoxLayout * costLayout = new QHBoxLayout{ cost };
    QLabel * costLabel = new QLabel{ "Cost: " };
    QLabel * costValue = new QLabel{ QString::fromStdString( doubleToUnits( 0 ) ) };
    costValue->setObjectName( "OrbCost" );
    QLabel * costIcon = new QLabel{};
    costIcon->setPixmap( QPixmap{ ":/product/Power" }.scaledToHeight( 18, Qt::SmoothTransformation ) );
    costLayout->setMargin( 0 );
    costLayout->addWidget( costLabel );
    costLayout->addWidget( costValue );
    costLayout->addWidget( costIcon );

    orbButton = new QToolButton{ this };
    orbButton->setText( "Open power orb" );
    orbButton->setSizePolicy( QSizePolicy::Policy::Preferred, QSizePolicy::Policy::Fixed );

    connect( orbSpinBox, QOverload<int>::of( &QSpinBox::valueChanged ), orbButton, [this]( int a ) { orbButton->setEnabled( a != orbSpinBox->maximum() ); } );
    connect( orbButton, &QToolButton::released, orbSpinBox, &QSpinBox::stepUp );

    QVBoxLayout * layout = new QVBoxLayout{ this };
    layout->addWidget( orbSpinBox );
    layout->addWidget( cost );
    layout->addWidget( orbButton );
}

void PowerOrbWidget::updateData( const State & state ) {
    if ( orbSpinBox->value() < 30 )
    {
        cost->show();
        double nextCost = ( 1.0 - static_cast<double>( state.getType( UpgradeType::Cost_Reduction_Orb ).getLevel() ) / 100 )
                          * static_cast<double>( PowerOrb::priceList().at( static_cast<size_t>( 1 + orbSpinBox->value() ) ) );
        cost->findChild<QLabel *>( "OrbCost" )->setText( QString::fromStdString( doubleToUnits( nextCost ) ) );
    } else
    { cost->hide(); }
}

